package com.mall.canal.listener;

import com.alibaba.fastjson.JSON;
import com.mall.page.feign.SeckillPageFeign;
import com.mall.search.feign.SeckillGoodsSearchFeign;
import com.mall.search.model.SeckillGoodsEs;
import com.mall.seckill.model.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

/**
 * @author Darren
 * @date 2022-08-22 15:48
 * Description：
 */
@Component
@CanalTable("seckill_goods")
public class SeckillGoodsHandler implements EntryHandler<SeckillGoods> {
    @Autowired
    private SeckillGoodsSearchFeign seckillGoodsSearchFeign;
    @Autowired
    private SeckillPageFeign seckillPageFeign;

    @Override
    public void insert(SeckillGoods seckillGoods) {
        seckillGoodsSearchFeign.add(JSON.parseObject(JSON.toJSONString(seckillGoods), SeckillGoodsEs.class));
        // 生成/更新静态页
        try {
            seckillPageFeign.page(seckillGoods.getId());
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(SeckillGoods before, SeckillGoods after) {
        // 索引导入
        seckillGoodsSearchFeign.add(JSON.parseObject(JSON.toJSONString(after), SeckillGoodsEs.class));
        // 生成/更新静态页
        try {
            seckillPageFeign.page(after.getId());
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(SeckillGoods seckillGoods) {
        EntryHandler.super.delete(seckillGoods);
    }
}
